const express = require("express");
const route = express.Router(); // 实例化一个路由对象

// 引入连接池
const pool = require("../../sql/index");
// const expressJWT = require('express-jwt')
const jwt = require("jsonwebtoken");
const secretKey = require("../../util/const").secretKey;
const decrypt = require("../../tools/comJs").decrypt;
const routes = require("../../reptile/routes");
// 登录接口
route.post("/sys/login", (req, res) => {
  pool.getConnection(function(err, connection) {
    if (err) {
      throw err;
    }
    // 将 req.body 请求体中的数据，转存为 userinfo 常量
    const userinfo = req.body;
    const sql = `select id,userName from users where userName ='${
      userinfo.username
    }' AND passWord ='${decrypt(userinfo.password)}' limit 1;`;
    console.log("拼接的sql", sql);
    connection.query(sql, function(error, results, fields) {
      connection.release();
      if (results.length > 0) {
        const { id, userName } = results[0];
        const tokenStr = jwt.sign({ id, userName }, secretKey, {
          expiresIn: "1h"
        });
        res.send({
          status: 200,
          code: 1,
          msg: "登录成功！",
          data: { ...results[0], token: tokenStr, routes }
        });
      } else {
        let apiRes = {
          code: 0,
          msg: "登录失败！",
          data: results
        };
        res.send(apiRes);
      }
    });
  });
});

module.exports = route; // 暴露出去方便管理
